package com.phkj.qdh.ui.fragment.usecar

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.core.os.bundleOf
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import com.chad.library.adapter4.QuickAdapterHelper
import com.chad.library.adapter4.loadState.LoadState
import com.chad.library.adapter4.loadState.trailing.TrailingLoadStateAdapter
import com.hjq.toast.ToastUtils
import com.phkj.qdh.R
import com.phkj.qdh.bean.PageInfo
import com.phkj.qdh.databinding.FragmentUseCarSubmitSelectCarBinding
import com.phkj.qdh.ui.adapter.UseCarSubmitSelectCarAdapter
import com.phkj.qdh.utils.LogUtil
import com.phkj.qdh.utils.PAGE_SIZE
import com.phkj.qdh.utils.launchAndRepeatWithViewLifecycle
import kotlinx.coroutines.flow.collectLatest
import rxhttp.wrapper.utils.GsonUtil

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * 选择车辆
 */
class UseCarSubmitSelectCarFragment : Fragment() {
    private var param1: String? = null
    private var param2: String? = null
    private var _binding: FragmentUseCarSubmitSelectCarBinding? = null
    private lateinit var vm: CarVM
    private val carKeyPageInfo = PageInfo()
    private val binding get() = _binding!!
    private val useCarSubmitSelectCarAdapter by lazy { UseCarSubmitSelectCarAdapter() }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
        requireActivity().onBackPressedDispatcher.addCallback(
            this,
            object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                    parentFragmentManager.popBackStack(
                        "car_select", FragmentManager.POP_BACK_STACK_INCLUSIVE
                    )
                }
            })
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        _binding = FragmentUseCarSubmitSelectCarBinding.inflate(inflater, container, false)
        vm = ViewModelProvider(this, getCarVMProvider())[CarVM::class.java]
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.run {
            rvCar.run {
                layoutManager = GridLayoutManager(requireContext(), 3)
                adapter = useCarSubmitSelectCarAdapter
            }
            btnSubmit.setOnClickListener {
                parentFragmentManager.popBackStack(
                    "car_select", FragmentManager.POP_BACK_STACK_INCLUSIVE
                )
            }
            srlCar.setOnRefreshListener {
                refreshUseCarList()
            }
            ivBack.setOnClickListener {
                parentFragmentManager.popBackStack(
                    "car_select", FragmentManager.POP_BACK_STACK_INCLUSIVE
                )
            }
            btnSubmit.setOnClickListener {
                val data = useCarSubmitSelectCarAdapter.items.filter { it.isSelected }

                if (data.size > 0) {
                    parentFragmentManager.setFragmentResult(
                        "car_select", bundleOf("list" to GsonUtil.toJson(data))
                    )
                    parentFragmentManager.popBackStack(
                        "car_select", FragmentManager.POP_BACK_STACK_INCLUSIVE
                    )
                }else{
                    ToastUtils.show("请先选择车辆")
                }
            }
        }


        /* carKeyHelper = QuickAdapterHelper.Builder(useCarSubmitSelectCarAdapter)
             .setTrailingLoadStateAdapter(object : TrailingLoadStateAdapter.OnTrailingListener {
                 override fun onFailRetry() {
                     getCarKeyList()
                 }

                 override fun onLoad() {
                     carKeyPageInfo.nextPage()
                     getCarKeyList()
                 }

                 override fun isAllowLoading(): Boolean {
                     return !binding.srlCar.isRefreshing
                 }
             }).build()*/
//        binding.rvCar.adapter = carKeyHelper.adapter
        useCarSubmitSelectCarAdapter.setOnItemClickListener { adapter, _, pos ->
            adapter.getItem(pos)!!.isSelected = !adapter.getItem(pos)!!.isSelected
            useCarSubmitSelectCarAdapter.notifyItemChanged(pos)
        }

        launchAndRepeatWithViewLifecycle {
            vm.carKey.collectLatest {
                binding.srlCar.isRefreshing = false
                useCarSubmitSelectCarAdapter.submitList(it)/* if (carKeyPageInfo.isFirstPage) {
                    useCarSubmitSelectCarAdapter.submitList(it)
                } else {
                    useCarSubmitSelectCarAdapter.addAll(it)
                }

                if (it.size != PAGE_SIZE) {*//*

                    Set the status to not loaded, and there is no paging data.
                    设置状态为未加载，并且没有分页数据了
                     *//*
                    carKeyHelper.trailingLoadState = LoadState.NotLoading(true)
                } else {*//*
                    Set the state to not loaded, and there is also paginated data
                    设置状态为未加载，并且还有分页数据
                     *//*
                    carKeyHelper.trailingLoadState = LoadState.NotLoading(false)
                }
            */
            }
        }
        getCarKeyList()
    }

    private fun getCarKeyList() {
        val map = HashMap<String, Any?>()
//        map["page"] = carKeyPageInfo.page
//        map["size"] = PAGE_SIZE
        vm.getCarKeyList(map)
    }

    private fun refreshUseCarList() {
        LogUtil.E("刷新")
        carKeyPageInfo.reset()
//        carKeyHelper.trailingLoadState = LoadState.None
        getCarKeyList()
    }

    companion object {
        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @param param1 Parameter 1.
         * @param param2 Parameter 2.
         * @return A new instance of fragment UseCarSubmitSelectCarFragment.
         */
        // TODO: Rename and change types and number of parameters
        @JvmStatic
        fun newInstance(param1: String, param2: String) = UseCarSubmitSelectCarFragment().apply {
            arguments = Bundle().apply {
                putString(ARG_PARAM1, param1)
                putString(ARG_PARAM2, param2)
            }
        }
    }
}